Using .match(/\w+/g).length while counting the number of words, returns an error if space is given at beginning of a sentence. How do i make it error-free?
The error says "can't read the properties of null (reading 'length')"
match returns null when no matches were found. In your case, it is when there are no words (empty strings or just white spaces). In other cases, it is an array.
You should check if the result of the match is null before checking the .length.
One way to overcome this error, suppose str is the string you are checking:
const matchStr = str.match(/\w+/g) || []; // The || [] will give you empty array instead of null when no matches were found
matchStr.length // now you can safely use .length property, because you will always have an array.
Try this str.match(/(\w+)/g).length